﻿using DAMS.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace DAMS.Data
{
    public class DbCon : IdentityDbContext<AppUser,AppRole,int>
    {
        private readonly IConfiguration config;

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if(!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseMySql(@"server=172.16.56.110;user id=dabftop;database=dabftop;pwd=Mysql-123456;port=3306;CharSet=utf8mb4;");
            }
        }

      
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.Entity<AppUser>().ToTable("AppUsers");
            builder.Entity<AppRole>().ToTable("AppRoles");
            builder.Entity<IdentityUserLogin<int>>().ToTable("AppUserLogins");
            builder.Entity<IdentityUserToken<int>>().ToTable("AppUserTokens");
            builder.Entity<IdentityUserClaim<int>>().ToTable("AppUserClaims");
            builder.Entity<IdentityRoleClaim<int>>().ToTable("AppRoleClaims");
            builder.Entity<IdentityUserRole<int>>().ToTable("AppUserRoles");

            //builder.Entity<Tag>().HasKey(t => t.TagName);//指定TagName为主键
            //builder.Entity<Tag>().HasAlternateKey(t => t.TagName);//指定备用键，唯一性约束:如果使用备用键，则不能修改
            builder.Entity<ArticleTag>()
           .HasKey(t => new {t.ArticleID,t.TagID});

            builder.Entity<ArticleTag>()
                .HasOne(at => at.Article)
                .WithMany(a => a.ArticleTags)
                .HasForeignKey(at => at.ArticleID);

            builder.Entity<ArticleTag>()
                .HasOne(at => at.Tag)
                .WithMany(t => t.ArticleTags)
                .HasForeignKey(at => at.TagID);

            builder.Entity<Category>().HasData(new Category()
            {
                ID = 1,
                Name = "root",
                Layer = 0,
                ParentID = 0,
                LeftNum = 0,
                RightNum = 3,
                Type= CategoryType.Top,
                ShowType=2
            },
            new Category()
            {
                ID = 2,
                Name = "首页",
                Layer = 1,
                ParentID = 1,
                LeftNum = 1,
                RightNum = 2,
                Type= CategoryType.Home,
                Template="Index",
                ShowType = 2

            });
               
            
            
        }

        public DbCon(DbContextOptions<DbCon> options,IConfiguration config)
            : base(options)
        { this.config = config; }


        public DbSet<Article> Articles { get; set; }
        public DbSet<Category> Categorys { get; set; }

        public DbSet<Tag> Tags { get; set; }

    }
}
